package com.xxoo.mycollect.utils;

import java.lang.reflect.Method;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.AsyncTask;

public class SkinPackageManager {

	private static SkinPackageManager mInstance;
	private Context mContext;

	public String mPackageName;
	public Resources mResources;

	private SkinPackageManager(Context context) {
		this.mContext = context;
	}

	public static SkinPackageManager getInstance(Context mContext) {
		if (mInstance == null) {
			mInstance = new SkinPackageManager(mContext);
		}
		return mInstance;
	}

	public void loadSkinAsync(String dexPath, final loadSkinCallBack callback) {
		new AsyncTask<String, Void, Resources>() {

			@Override
			protected void onPreExecute() {

				if (callback != null) {
					callback.sartloadSkin();
				}
			};

			@Override
			protected Resources doInBackground(String... params) {
				try {
					if (params.length == 1) {
						String dexPath_tmp = params[0];
						PackageManager mPm = mContext.getPackageManager();
						PackageInfo mInfo = mPm.getPackageArchiveInfo(
								dexPath_tmp, PackageManager.GET_ACTIVITIES);
						mPackageName = mInfo.packageName;

						AssetManager assetManager = AssetManager.class
								.newInstance();
						Method addAssetPath = assetManager.getClass()
								.getMethod("addAssetPath", String.class);
						addAssetPath.invoke(assetManager, dexPath_tmp);

						Resources superRes = mContext.getResources();
						Resources skinResource = new Resources(assetManager,
								superRes.getDisplayMetrics(),
								superRes.getConfiguration());
						// SkinConfig.getInstance(mContext).setSkinResourcePath(
						// dexPath_tmp);
						return skinResource;
					}
					return null;
				} catch (Exception e) {
					return null;
				}
			}

			@Override
			protected void onPostExecute(Resources result) {
				mResources = result;
				if (callback != null) {
					if (result != null) {
						callback.loadSkinSuccess();
					} else {
						callback.sartloadSkin();
					}
				}
			}
		};
	}

	public interface loadSkinCallBack {
		public void sartloadSkin();

		public void loadSkinSuccess();

		public void loadSkinFail();
	}
}
